/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

/**
 Do not return anything, modify head in-place instead.
 */
 function reorderList(head: ListNode | null) {
    let len = 0;
    for(let p = head; p !== null; p = p.next) {
        len++;
    }
    let reverseLength = len >> 1;
    let fast = head, slow = head;
    for(let i = 0; i < reverseLength; i++) {
        fast = fast.next;
    }
    while(fast.next !== null) {
        fast = fast.next;
        slow = slow.next;
    }
    // console.log(fast);
    // console.log(slow);

    let prev = null;
    let cur = slow.next;
    slow.next = null;
    
    while(prev !== fast && cur) {
        let nxt = cur.next;
        cur.next = prev;
        prev = cur;
        cur = nxt;
    }

    while(prev) {
        let hNext = head.next;
        head.next = prev;
        head = hNext;
        let pNext = prev.next;
        prev.next = head;
        prev = pNext;
    }
    return head;
};

let c = {
    val: 1,
    next: {
        val: 2,
        next: {
            val: 3,
            next: {
                val: 4,
                next: null
            }
        }
    }
}

console.log(reorderList(c));